package com.es.designmode.prototype;

import java.io.*;

/**
 * 原型模式
 * 简而言之，就是通过复制实现
 *
 * @author Will
 */
public abstract class Prototype implements Serializable, Cloneable {

    private TmpObj tmpObj;

    public TmpObj getTmpObj() {
        return tmpObj;
    }

    public void setTmpObj(TmpObj tmpObj) {
        this.tmpObj = tmpObj;
    }

    private String id;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private int age;

    public Prototype(String id) {
        this.id = id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    @Override
    public Object clone() {
        return deepClone();
    }

    /**
     * 深克隆
     *
     * @return 克隆对象
     */
    public Object deepClone() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);                                          // 写到当前类，当然也可以写入文件
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());    // 字节输出流
            ObjectInputStream ois = new ObjectInputStream(bais);            // 输出该对象
            return ois.readObject();                                        // 读出对象，实现新对象的生成
        } catch (Exception e) {
            System.err.println("克隆出错：" + e.getStackTrace());
            return null;
        }
    }

    /**
     * 浅克隆
     *
     * @return 浅克隆对象
     * @throws CloneNotSupportedException
     */
    public Object shallowClone() throws CloneNotSupportedException {
        return super.clone();
    }
}
